<script setup lang="ts">
import { getHouseById, getHouseImgById, reserveHouse } from '~/api/house'
import { getCommentsByHouseId } from '~/api/comment'
import { getPropertiesByHouseIdAPI } from '~/api/houseProperty'
import { checkIsStarAPI, deleteStarAPI, starHouseAPI } from '~/api/houseStar'

const userString = localStorage.getItem('userInfo') as string
const user = JSON.parse(userString)
const route = useRoute()
const router = useRouter()

const id = route.params.id

const comments = ref([])
const imgs = ref<any>([])
const house = ref<any>([])
const property = ref<any>([])
const adultNum = ref(1)
const childNum = ref(0)
const startTime = ref('')
const endTime = ref('')
const days = ref(0)
const date = ref('')
const isLogin = ref(false)
const isStar = ref(false)

if (user !== null)
  isLogin.value = true

function change(data: any) {
  startTime.value = data[0]
  endTime.value = data[1]
  const date1 = new Date(data[0])
  const date2 = new Date(data[1])
  const diff = Math.abs(Number(date2) - Number(date1))
  days.value = Math.ceil(diff / (1000 * 60 * 60 * 24))
}

async function handleStar() {
  isStar.value = !isStar.value
  if (isStar.value) {
    await starHouseAPI(user.id, id).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: '收藏成功！',
          type: 'success',
        })
      }
    })
  }
  else {
    await deleteStarAPI(user.id, id).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: '取消收藏！',
          type: 'success',
        })
      }
    })
  }
}

function handleChangeAdultNum(value: any) {
  adultNum.value = value
}
function handleChangeChildNum(value: any) {
  childNum.value = value
}

async function handleReserve() {
  if (user !== null) {
    const reserve = {
      adultNum: adultNum.value,
      childNum: childNum.value,
      userId: user.id,
      houseId: route.params.id,
      startTime: startTime.value,
      endTime: endTime.value,
    }
    if (reserve.startTime !== '' && reserve.endTime !== '') {
      await reserveHouse(reserve).then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            message: '预定成功，请到个人中心完成支付！',
            type: 'success',
          })
          init()
        }
      })
    }
    else {
      ElMessage({
        message: '请选择入住时间！',
        type: 'error',
      })
    }
  }
  else {
    ElMessage({
      message: `请先登录！`,
      type: 'error',
      showClose: true,
      center: true,
    })
    router.push('/login')
  }
}

async function init() {
  await getHouseImgById(id).then(((res: any) => {
    if (res.code === 200)
      imgs.value = res.result
  }))
  await getHouseById(id).then(((res: any) => {
    if (res.code === 200)
      house.value = res.result
  }))
  await getCommentsByHouseId(id).then(((res: any) => {
    if (res.code === 200)
      comments.value = res.result
  }))
  await getPropertiesByHouseIdAPI(id).then(((res: any) => {
    if (res.code === 200)
      property.value = res.result
  }))
  await checkIsStarAPI(user.id, id).then(((res: any) => {
    if (res.code === 200)
      isStar.value = true
  }))
}
init()
</script>

<template>
  <div class="main pt-2">
    <div class="flex justify-between">
      <div text="2xl" class="font-bold">
        {{ house.title }}
      </div>

      <div v-if="isStar" flex class="mr-4 cursor-pointer p-1 transition delay-100 ease-in-out hover:bg-[#f7f7f7]" @click="handleStar">
        <div class="mr-1">
          已收藏
        </div>
        <img class="h-6 w-6" src="/star_red.png">
      </div>
      <div v-else flex class="mr-4 cursor-pointer p-1 transition delay-100 ease-in-out hover:bg-[#f7f7f7]" @click="handleStar">
        <div class="mr-1">
          收藏
        </div>
        <img class="h-6 w-6" src="/star.png">
      </div>
    </div>

    <div class="parent">
      <div class="div1">
        <el-image
          style="width: 550px; height: 350px;border-radius: 15px 0 0 15px;"
          :src="imgs[0]"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="imgs"
          :initial-index="0"
          fit="cover"
        />
      </div>
      <div class="div2">
        <el-image
          style="width: 280px; height: 170px"
          :src="imgs[1]"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="imgs"
          :initial-index="1"
          fit="cover"
        />
      </div>
      <div class="div3">
        <el-image
          style="width: 280px; height: 170px;border-radius:  0 15px 0 0;"
          :src="imgs[2]"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="imgs"
          :initial-index="2"
          fit="cover"
        />
      </div>
      <div class="div4">
        <el-image
          style="width: 280px; height: 170px"
          :src="imgs[3]"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="imgs"
          :initial-index="3"
          fit="cover"
        />
      </div>
      <div class="div5">
        <el-image
          style="width: 280px; height: 170px;border-radius:  0 0 15px 0;"
          :src="imgs[4]"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="imgs"
          :initial-index="4"
          fit="cover"
        />
      </div>
    </div>
    <el-row :gutter="20">
      <el-col :span="14">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <span>
              <el-icon><LocationFilled /></el-icon>
            </span>
            <span class="pb-1 pl-1 font-bold">
              {{ house.address }}
            </span>
          </div>
          <div class="flex pb-3 pr-6">
            <span v-if="house.rest > 0">
              <el-tag>有房</el-tag>
            </span>
            <span v-else>
              <el-tag type="danger">预约已满</el-tag>
            </span>
            <div class="pl-2">
              <el-tag type="warning">
                最多入住：{{ house.maxAdu }}人
              </el-tag>
            </div>
          </div>
        </div>

        <p>{{ house.des }}</p>

        <el-divider />
        <p text="xl" class="mb-5 font-bold">
          房源亮点与便利设施
        </p>

        <div class="volume-wrapper">
          <div v-for="item in property" :key="item.id" class="volume-item">
            <el-image style="width: 50px; height: 50px; vertical-align: middle; " :src="item.icon" fit="fill" />
            {{ item.name }}
          </div>
        </div>
        <el-divider />
        <p text="xl" class="mb-5 font-bold">
          预订须知
        </p>
        <div>{{ house.notice }}</div>
        <el-divider />

        <div>
          <Comment :comment="comments" />
        </div>
      </el-col>
      <el-col :span="10">
        <div class="flex justify-between pb-3">
          <span text="2xl" class="font-bold">
            {{ house.price }}￥/晚
          </span>
          <span>♥ {{ house.stars }}</span>
        </div>

        <!-- 房间预定 -->
        <el-card class="mb-4 flex justify-center align-middle">
          <div class="block">
            <el-date-picker
              v-model="date"
              type="daterange"
              range-separator="To"
              start-placeholder="入住日期"
              end-placeholder="退房日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="change"
            />
            <div class="people">
              成人 <el-input-number
                v-model="adultNum"
                style="float: right"
                :min="1"
                :max="house.maxAdu"
                @change="handleChangeAdultNum"
              />
            </div>
            <div class="people">
              儿童
              <el-input-number
                v-model="childNum"
                style="float: right"
                :min="0"
                :max="10"
                @change="handleChangeChildNum"
              />
            </div>
            <el-divider />
            <div class="pb-2">
              <span class="font-bold">总计：</span> ￥{{ house.price }}/晚 x
              {{ days }} 晚 =
              <span class="text-red-500 font-bold">￥{{ house.price * days }}</span>
            </div>
            <div class="pb-2">
              <span class="font-bold">剩余房间：</span>{{ house.rest }}间
            </div>

            <el-button
              type="danger"
              class="w-full bg-red-600"
              :disabled="house.rest <= 0"
              @click="handleReserve"
            >
              预定
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.volume-wrapper {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.volume-item {
  margin-bottom: 10px;
  width: calc((100% - 0px) / 4);
}

.volume-item:nth-of-type(4n + 0) {
  margin-right: 0;
}

.main {
  padding: 10px 45px;
}
.people {
  padding: 8px;
}
.parent {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-column-gap: 0px;
  grid-row-gap: 0px;
  padding: 15px 0;
}

.div1 {
  grid-area: 1 / 1 / 3 / 3;
}
.div2 {
  grid-area: 1 / 3 / 2 / 4;
}
.div3 {
  grid-area: 1 / 4 / 2 / 5;
}
.div4 {
  grid-area: 2 / 3 / 3 / 4;
}
.div5 {
  grid-area: 2 / 4 / 3 / 5;
}
.demonstration {
  color: var(--el-text-color-secondary);
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
</style>
